from time import sleep

import pytest
import requests

import config.path_cfg as path_cfg
from api.reg_login_api import RegLoginApi
from common.util import read_xlsx, common_assert, clear_user_info, build_account


class TestRegLogin(object):

    def setup_class(self):
        build_account('open_user', requests.Session(), path_cfg.REG_LOGIN_PHONE)

    def setup(self):
        self.session = requests.Session()
        self.reg_login_api = RegLoginApi(self.session)

    def teardown(self):
        self.session.close()

    # 获取图片验证码测试用例
    @pytest.mark.run(order=1)
    @pytest.mark.parametrize('title,body,expect', read_xlsx('P2P金融项目-接口测试用例.xlsx', '登录注册', 2, 3))
    def test_img_verify_code(self, title, body, expect):
        resp = self.reg_login_api.get_img_verify_code(body.get('path_param'))

        assert expect.get('status_code') == resp.status_code

    # 获取短信验证码测试用例
    @pytest.mark.run(order=2)
    @pytest.mark.parametrize('title,body,expect', read_xlsx('P2P金融项目-接口测试用例.xlsx', '登录注册', 4, 6))
    def test_phone_verify_code(self, title, body, expect):
        clear_user_info(body.get('phone'))

        self.reg_login_api.get_img_verify_code('1')

        resp = self.reg_login_api.get_sms_verify_code(body)

        common_assert(expect, resp)

    # 注册测试用例
    @pytest.mark.run(order=3)
    @pytest.mark.parametrize('title, body, expect', read_xlsx('P2P金融项目-接口测试用例.xlsx', '登录注册', 7, 15))
    def test_register(self, title, body, expect):
        if '手机已存在' not in title:
            clear_user_info(body.get('phone'))

        self.reg_login_api.get_img_verify_code('1')

        req_body = {
            "phone": body.get('phone'),
            "imgVerifyCode": "8888",
            "type": "reg"
        }
        self.reg_login_api.get_sms_verify_code(req_body)

        resp = self.reg_login_api.user_register(body)

        common_assert(expect, resp)

    # 登录测试用例
    @pytest.mark.run(order=4)
    @pytest.mark.parametrize('title,body,expect', read_xlsx('P2P金融项目-接口测试用例.xlsx', '登录注册', 16, 19))
    def test_user_login(self, title, body, expect):
        resp = self.reg_login_api.user_login(body)

        common_assert(expect, resp)

    # 登录测试用例-密码错误校验，在一条用例内执行，不能使用参数化
    @pytest.mark.run(order=5)
    @pytest.mark.skip('x')
    def test_user_login_verify(self):
        params_data = read_xlsx('P2P金融项目-接口测试用例.xlsx', '登录注册', 20, 22)

        for i in params_data:
            resp = self.reg_login_api.user_login(i[1])
            common_assert(i[2], resp)

        sleep(60)
        params_data = read_xlsx('P2P金融项目-接口测试用例.xlsx', '登录注册', 23, 23)
        resp = self.reg_login_api.user_login(params_data[0][1])
        common_assert(params_data[0][2], resp)
